/*
 * Name: Joon Ho Cho
 * Date: 10/24/2008
 * Course: 15-437
 */
package scheduler.controller;


import javax.servlet.http.HttpServletRequest;


import org.mybeans.dao.DAOException;


import scheduler.databean.Course;
import scheduler.databean.Lecture;
import scheduler.databean.Section;
import scheduler.model.CourseDao;
import scheduler.model.LectureDao;
import scheduler.model.Model;
import scheduler.model.SectionDao;



public class CourseAction extends Action {

	private CourseDao courseDao;
	private SectionDao sectionDao;
	private LectureDao lectureDao;

	public CourseAction(Model model) {

		courseDao = model.getCourseDao();
		sectionDao= model.getSectionDao();
		lectureDao=model.getLectureDao();
	}

	public String getName() { return "course.do"; }

	public String perform(HttpServletRequest request) {
		try {
			String secTable="";
			int CourseID = Integer.parseInt(request.getParameter("course"));

			Course course= courseDao.lookup(CourseID);

			Section[] section =sectionDao.getSectionForCourse(CourseID);

			secTable+="<table>"   ;

			Lecture lec=null;
			Lecture prev=null;
			for(int i=0; i<section.length; i++)
			{
				Section s=section[i];				
				if(s.getLectureId()!=-1)
				{
					lec=lectureDao.lookup(s.getLectureId());
					if(prev==null || !(lec.getLectureNumber().equals(prev.getLectureNumber())))
					{
						System.out.println("lec"+lec.getLectureNumber());
						if(prev!=null)
						System.out.println("prve"+prev.getLectureNumber());
						secTable+="<tr>";
						secTable+= "<td class=\"lecture\"> Lec"+lec.getLectureNumber()+"</td>";
						secTable+="<td class=\"days\">" +lec.getDay()[0]+ "</td>";
						secTable+="<td class=\"time\">" +lec.getStartTime()[0]+ "</td>";
						secTable+="<td class=\"room\">" +lec.getClassroom()[0]+ "</td>";
						secTable+="<td class=\"instructor\">" +lec.getInstructor()+ "</td>";
						secTable+="</tr>";

					}
					secTable+="<tr>";
					secTable+= "<td class=\"section\"> Lec"+s.getSectionName()+"</td>";
					secTable+="<td class=\"days\">" +s.getDay()[0]+ "</td>";
					secTable+="<td class=\"time\">" +s.getStartTime()[0]+ "</td>";
					secTable+="<td class=\"room\">" +s.getClassroom()[0]+ "</td>";
					secTable+="<td class=\"instructor\">" +s.getInstructor()+ "</td>";
					secTable+="</tr>";       		   

				}
				prev=lec;

			}
			secTable+="</table>" ;

			request.setAttribute("course", course);
			request.setAttribute("sectable", secTable);


			return "course.jsp";

		} catch (DAOException e) {
			e.printStackTrace();
			request.setAttribute("dbError",e.getMessage());
			return "db-error.jsp";
		}
	}
}
